/**
  ******************************************************************************
  * @file    
  * @author  
  * @version 
  * @date    
  * @brief  
  ******************************************************************************
	* @attention
  *
  * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2>
  *
  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  * You may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  *
  *        http://www.st.com/software_license_agreement_liberty_v2
  *
  * Unless required by applicable law or agreed to in writing, software 
  * distributed under the License is distributed on an "AS IS" BASIS, 
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  ******************************************************************************
  */

#include "hwconf.h"

/**
  * @brief  Configures the clock subsystem.
  * @param  None
  * @retval None
  */
void RTC_Config(void)
{
	/* Power enable */
  *(__IO uint32_t *) RCC_APB1ENR_PWREN_BB = (uint32_t)SET;
  
  /* Allow access to RTC */
  PWR_RTCAccessCmd(ENABLE);

  /* Reset RTC domain */
  RCC_RTCResetCmd(ENABLE);
  RCC_RTCResetCmd(DISABLE);

  /* LSE enable */
  RCC_LSEConfig(RCC_LSE_ON);

  /* Wait till LSE is ready */
  while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET)
  {}

  /* RTC clock source selection */
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
	
	/* Enable the RTC Clock */
  RCC_RTCCLKCmd(ENABLE);

  /* Wait for RTC APB registers synchronisation */
  RTC_WaitForSynchro();

  /* Clear Wake-up flag */
  PWR->CR |= PWR_CR_CWUF;
	  
  /* Clear RTC Interrupt pending bit */
  RTC_ClearITPendingBit(RTC_IT_WUT);

  /* Enable the Wakeup Interrupt */
  RTC_ITConfig(RTC_IT_WUT, ENABLE);
	
	/* Power disable */
  *(__IO uint32_t *) RCC_APB1ENR_PWREN_BB = (uint32_t)RESET;
}

/**
  * @brief  Configures the RTC Wake-Up timer.
  * @param  time_ms: Time to wake-up in miliseconds
  * @retval None
  */
void RTC_SetWakeUp(__IO uint32_t time_ms)
{
	if (time_ms >= 30000)
	{		
    /* Configure the RTC WakeUp Clock source: CK_SPRE (1Hz) */
    RTC_WakeUpClockConfig(RTC_WakeUpClock_CK_SPRE_16bits);
	
	  /* Set Wakeup auto-reload value */
    RTC_SetWakeUpCounter(time_ms / 1000);
	}
	else if ((time_ms >= 1000) && (time_ms < 30000))
	{
		/* Configure the RTC WakeUp Clock source: CK_SPRE (1Hz) */
    RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div16);
	
	  /* Set Wakeup auto-reload value */
    RTC_SetWakeUpCounter(((2048 * time_ms) / 1000) - 1);
	}
	else {
		/* Configure the RTC WakeUp Clock source: CK_SPRE (1Hz) */
    RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div2);
	
	  /* Set Wakeup auto-reload value */
    RTC_SetWakeUpCounter(((16384 * time_ms) / 1000) - 1);
	}
}

/************************************** EOF *********************************/
